package com.terios.logic.ui;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.terios.Comment;
import com.terios.R;
import com.terios.Status;
import com.terios.conts.CommonStrs;
import com.terios.intfs.IWeiboActivity;
import com.terios.intfs.PullToRefresh;
import com.terios.intfs.PullToRefresh.UpdateHandle;
import com.terios.logic.MainService;
import com.terios.logic.Task;
import com.terios.logic.ui.adapter.CommentAdapter;
import com.terios.logic.ui.adapter.WeiboAdapter;
import com.terios.util.Exit;

/**
 * MSGActivity.java 2012-9-30 下午4:50:37
 * 
 * @author Wang Tengrui
 */
public class MSGActivity extends Activity implements IWeiboActivity, UpdateHandle {

	public static final int REFRESH_MENTIONS = 1;
	public static final int REFRESH_COMMENT = 2;
	public static final int REFRESH_MESSAGE = 3;
	public static final int REFRESH_NOTIFICATION = 4;
	private LinearLayout msg_at_layout, msg_comment_layout, msg_message_layout, msg_notification_layout;
	private ListView msg_at_list;// 微博信息显示
	private ListView msg_comment_list;// 评论
	private ListView msg_message_list;// 私信
	private ListView msg_notification_list;// 通知
	private View msgProgress;// 大菊花
	private LinearLayout more_button;// 底部更多项
	private ProgressBar bottom_progressBar;// 底部更多项的菊花
	private WeiboAdapter msgAtAdapter;// at当前登录用户的微博信息适配器
	private CommentAdapter msgCommentAdapter;// 评论信息适配器
	private RadioGroup radioGroup;
	public int atNowPage = 1;// 当前第几页
	public int commentsNowPage = 1;// 当前第几页
	public int messageNowPage = 1;// 当前第几页
	public int notificationNowPage = 1;// 当前第几页

	public int pageSize = CommonStrs.MAX_INFO_NUM;// 单页返回的记录条数，最大不超过200，默认为20
	PullToRefresh pullToRefresh;

	@SuppressWarnings("static-access")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(getWindow().FEATURE_NO_TITLE);// 取消标题显示
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_msg);
		initview();
		MainService.allActivity.add(this);
		init();// 开始请求数据
	}

	/**
	 * 初始化布局
	 */
	private void initview() {

		pullToRefresh = (PullToRefresh) this.findViewById(R.id.msg_at_pullDownView);
		pullToRefresh.setUpdateHandle(this);

		radioGroup = (RadioGroup) this.findViewById(R.id.msg_group);
		msg_at_layout = (LinearLayout) this.findViewById(R.id.msg_at_layout);
		msg_comment_layout = (LinearLayout) this.findViewById(R.id.msg_comment_layout);
		msg_message_layout = (LinearLayout) this.findViewById(R.id.msg_message_layout);
		msg_notification_layout = (LinearLayout) this.findViewById(R.id.msg_notification_layout);
		radioGroup.setOnCheckedChangeListener(listener);
		radioGroup.check(R.id.msg_group_at);

		msgProgress = this.findViewById(R.id.msg_progress);// 查找大菊花View
		msg_at_list = (ListView) this.findViewById(R.id.msg_at_list);
		msg_comment_list = (ListView) this.findViewById(R.id.msg_comment_list);
		msg_message_list = (ListView) this.findViewById(R.id.msg_message_list);
		msg_notification_list = (ListView) this.findViewById(R.id.msg_notification_list);

		View bottom = LayoutInflater.from(this).inflate(R.layout.itembottom, null);//动态加载
		bottom_progressBar = (ProgressBar) bottom.findViewById(R.id.progressBar);// 底部菊花
		msg_at_list.addFooterView(bottom);// 将菊花添加到ListView底部
		msg_comment_list.addFooterView(bottom);// 将菊花添加到ListView底部
		msg_message_list.addFooterView(bottom);// 将菊花添加到ListView底部
		msg_notification_list.addFooterView(bottom);// 将菊花添加到ListView底部

		more_button = (LinearLayout) bottom.findViewById(R.id.moreweibo);

		// 点击底部更多的布局
		more_button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				switch (radioGroup.getCheckedRadioButtonId()) {
				case R.id.msg_group_at:
					++atNowPage;// 请求页数加一
					init();// 再次请求
					bottom_progressBar.setVisibility(View.VISIBLE);// 菊花滚动起来
					break;
				case R.id.msg_group_comment:
					++commentsNowPage;// 请求页数加一
					init();// 再次请求
					bottom_progressBar.setVisibility(View.VISIBLE);// 菊花滚动起来
					break;
				}
			}
		});
		// 当我们点击 某一条微博信息的时候就可以跳转到信息页面
		msg_at_list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Status nowstu = (Status) parent.getAdapter().getItem(position);// 从适配器中获取当前点击项的内容
				Intent intent = new Intent(MSGActivity.this, WeiboInfo.class); // 发送到WeiboInfo
				intent.putExtra("status", nowstu);
				MSGActivity.this.startActivity(intent);
			}
		});
	}

	private OnCheckedChangeListener listener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			switch (checkedId) {
			case R.id.msg_group_at:
				msg_at_layout.setVisibility(View.VISIBLE);
				msg_comment_layout.setVisibility(View.GONE);
				msg_message_layout.setVisibility(View.GONE);
				msg_notification_layout.setVisibility(View.GONE);
				pullToRefresh = (PullToRefresh) MSGActivity.this.findViewById(R.id.msg_at_pullDownView);
				pullToRefresh.setUpdateHandle(MSGActivity.this);
				break;
			case R.id.msg_group_comment:
				msg_at_layout.setVisibility(View.GONE);
				msg_comment_layout.setVisibility(View.VISIBLE);
				msg_message_layout.setVisibility(View.GONE);
				msg_notification_layout.setVisibility(View.GONE);
				pullToRefresh = (PullToRefresh) MSGActivity.this.findViewById(R.id.msg_comment_pullDownView);
				pullToRefresh.setUpdateHandle(MSGActivity.this);
				if ( msgCommentAdapter == null) {
					init();// 开始请求数据
				}
				break;
			case R.id.msg_group_message:
				msg_at_layout.setVisibility(View.GONE);
				msg_comment_layout.setVisibility(View.GONE);
				msg_message_layout.setVisibility(View.VISIBLE);
				msg_notification_layout.setVisibility(View.GONE);
				pullToRefresh = (PullToRefresh) MSGActivity.this.findViewById(R.id.msg_message_pullDownView);
				pullToRefresh.setUpdateHandle(MSGActivity.this);
				break;
			case R.id.msg_group_notification:
				msg_at_layout.setVisibility(View.GONE);
				msg_comment_layout.setVisibility(View.GONE);
				msg_message_layout.setVisibility(View.GONE);
				msg_notification_layout.setVisibility(View.VISIBLE);
				pullToRefresh = (PullToRefresh) MSGActivity.this.findViewById(R.id.msg_notification_pullDownView);
				pullToRefresh.setUpdateHandle(MSGActivity.this);
				break;
			}
		}
	};

	@Override
	public void init() {
		switch (radioGroup.getCheckedRadioButtonId()) {
		case R.id.msg_group_at:
			
			// 请求参数
			HashMap<String, Integer> atParamHashMap = new HashMap<String, Integer>();
			atParamHashMap.put("nowPage", Integer.valueOf(atNowPage));
			atParamHashMap.put("pageSize", Integer.valueOf(pageSize));
			// 加载at当前用户的微博
			Task atTask = new Task(CommonStrs.TASK_GET_USER_MENTIONS, atParamHashMap);
			MainService.allTask.add(atTask);
			break;
		case R.id.msg_group_comment:
			// 请求参数
			HashMap<String, Integer> commentParamHashMap = new HashMap<String, Integer>();
			commentParamHashMap.put("nowPage", Integer.valueOf(commentsNowPage));
			commentParamHashMap.put("pageSize", Integer.valueOf(pageSize));
			// 加载评论
			Task commentsTask = new Task(CommonStrs.TASK_GET_USER_COMMENTS, commentParamHashMap);
			MainService.allTask.add(commentsTask);
			break;
		case R.id.msg_group_message:

			break;
		case R.id.msg_group_notification:

			break;
		}

	}

	/**
	 * 获取最新信息
	 */
	public void refresh() {
		switch (radioGroup.getCheckedRadioButtonId()) {
		case R.id.msg_group_at:
			atNowPage = 1;// 将当前页重置为第一页
			init();// 这里就是再次请求第一页信息
			break;
		case R.id.msg_group_comment:
			commentsNowPage = 1;// 将当前页重置为第一页
			init();// 这里就是再次请求第一页信息
			break;
		case R.id.msg_group_message:
			messageNowPage = 1;// 将当前页重置为第一页
			init();// 这里就是再次请求第一页信息
			break;
		case R.id.msg_group_notification:
			notificationNowPage = 1;// 将当前页重置为第一页
			init();// 这里就是再次请求第一页信息
			break;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void refresh(Object... param) {
		int flag = ((Integer) param[0]).intValue();// 获得任务标志
		switch (flag) {
		case REFRESH_MENTIONS:
			if (1 == atNowPage) {
				msgProgress.setVisibility(View.GONE);
				List<Status> mentionsStatus = (List<Status>) param[1];
				// 遍历检查数据
				for (int i = 0; i < mentionsStatus.size();) {
					if (mentionsStatus.get(i).getUser() == null) {
						mentionsStatus.remove(i);
					} else {
						i++;
					}
				}
				msgAtAdapter = new WeiboAdapter(this, mentionsStatus);
				msg_at_list.setAdapter(msgAtAdapter);
			} else {
				bottom_progressBar.setVisibility(View.GONE);
				List<Status> mentionsStatus = (List<Status>) param[1];
				// 遍历检查数据
				for (int i = 0; i < mentionsStatus.size();) {
					if (mentionsStatus.get(i).getUser() == null) {
						mentionsStatus.remove(i);
					} else {
						i++;
					}
				}
				msgAtAdapter.addmoreDate(mentionsStatus);
			}
			break;
		case REFRESH_COMMENT:
			if (1 == commentsNowPage) {
				msgProgress.setVisibility(View.GONE);
				List<Comment> comments = (List<Comment>) param[1];
				msgCommentAdapter = new CommentAdapter(this, comments);
				msg_comment_list.setAdapter(msgCommentAdapter);
			} else {
				bottom_progressBar.setVisibility(View.GONE);
				List<Comment> comments = (List<Comment>) param[1];
				msgCommentAdapter.addmoreDate(comments);
			}
			break;
		case REFRESH_MESSAGE:

			break;
		case REFRESH_NOTIFICATION:

			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Exit.btexit(MSGActivity.this);// 当我们按下返回键的时候要执行的动作
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	@Override
	public void onUpdate() {
		new PullRefreshThread(handler).start();
	}

	class PullRefreshThread extends Thread {
		private Handler handler;

		public PullRefreshThread(Handler handler) {
			this.handler = handler;
		}

		@Override
		public void run() {
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			Message msg = handler.obtainMessage();
			handler.sendMessage(msg);
			super.run();
		}
	}

	private final Handler handler = new Handler(Looper.getMainLooper()) {
		public void handleMessage(Message msg) { // 处理Message，更新ListView
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日   HH:mm:ss     ");
			refresh();
			Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
			String str = formatter.format(curDate);
			pullToRefresh.endUpdate(str);
		}
	};
}
